<template>
  <zsearch v-loading="loading">
      <template #date>
        <el-date-picker
            class="date-1"
            type="datetime"
            v-model="date"
            placeholder="选择日期"
            >
        </el-date-picker>
      </template>
      <template #select>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch">查询</el-button>
			  <el-button class="btn-2">导出</el-button>
			  <el-button class="btn-2" v-jurisdiction="'warehouse:process:add'"  @click="handleClickDrawer">新建计加工</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='groupData'
          width="260"
          :height="'100%'"
          :isshowOperation="true"

          @clickCell="clickCell"
        >
          <template #default="slotData">
            <el-select 
              v-jurisdiction="'warehouse:process:updateStatus'"
							class="select-3 machin-select" 
							v-model="slotData.rowData.status"  
							placeholder="请选择"
              @change="handleChange($event, slotData.rowData)"
							>
							<el-option
								v-for="i in options"
								:key="i.name"
								:label="i.name"
								:value="i.id">
							</el-option>
						</el-select>
            <el-button v-jurisdiction="'warehouse:process:update'" @click="handleEditItem(slotData.rowData)" type="text" size="small" class="operation" >修改</el-button>
            <el-button v-jurisdiction="'warehouse:process:del'" @click="handleDelItem(slotData.rowData)" type="text" size="small" class="operation" >删除</el-button>
          </template>
        </ztable>
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total" 
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>
    <zdrawer @handleClose="close" :title="title" v-model="openDrawer">
      <template #body>
        <ztitleBorder title="就诊详情">
            <!-- <div class="tem">
              <div class="tem-title">就诊项目</div>
              <el-select class="select-1" v-model="orderDetailId" placeholder="请选择病历">
                <el-option
                  v-for="item in orderDetail"
                  :key="item.id"
                  :label="item.itemName"
                  :value="item.id">
                </el-option>
            </el-select>
            </div> -->
            <div class="tem">
              <div class="tem-title">病历</div>
              <el-select class="select-1" v-model="medicalHistoryId" placeholder="请选择病历">
                <el-option
                  v-for="item in medicalOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
            <div class="tem">
              <div class="tem-title" style="padding: 0">订单编号</div>
              <el-input placeholder="请输入订单编号" v-model="processOrderCode"  class="input-2"></el-input>
            </div>
            <div class="tem">
              <div class="tem-title">取件人</div>
              <el-select class="select-1" v-model="consigneeId" placeholder="请选择取件人">
                <el-option
                  v-for="item in consigneeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
            <div class="tem">
              <div class="tem-title">医生</div>
              <el-select class="select-1" v-model="companyUserId" placeholder="请选择医生">
                <el-option
                  v-for="item in companyUserOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
            <div class="tem">
              <div class="tem-title">加工厂</div>
              <el-select class="select-1" v-model="processFactoryId" placeholder="请选择加工厂">
                <el-option
                  v-for="item in processFactoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
            </el-select>
            </div>
        </ztitleBorder>
        <ztitleBorder title="加工详情">
          <el-table
            :data="details"
            border
            style="width: 100%"
            height="300"
            >
            <el-table-column prop="processingItems" label="加工物品名称" width="180">
              <template #default="scope">
                <el-input placeholder="请输入名称" v-model="scope.row.processingItems"  class="input-2"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="processingFree"
              label="	加工物品价格"
              width="180"
              >
              <template #default="scope">
                <el-input placeholder="请输入价格" v-model="scope.row.processingFree"  class="input-2"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="orderDetailId"
              label="项目"
              width="180"
              >
              <template #default="scope">
                <el-select class="select-1" v-model="scope.row.orderDetailId" placeholder="请选择项目">
                <el-option
                    v-for="item in orderDetail"
                    :key="item.id"
                    :label="item.itemName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              align="right">
              <template #header>
                <el-button class="btn-1" @click="addProcess">新增</el-button>
              </template>
              <template #default="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </ztitleBorder>
      </template>
      <template #footer>
        <el-button class="btn-2" @click="cancel">取消</el-button>
        <el-button class="btn-1" @click="save">保存</el-button>
      </template>
    </zdrawer>
</template>

<script lang='ts'>
import { defineComponent, reactive, ref, toRefs, watch } from '@vue/runtime-core'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdrawer from "@components/drawer/drawer.vue";
import ztitleBorder from "../../components/titleBorder/titleBorder.vue"
import { debounce } from "../../utils/debounce"

import useRequet, { RespData } from "../../hook/network"
import useConfgin from '../../hook/getconfig'
import { ElMessage, ElMessageBox } from 'element-plus'

type OpearBtn = {
	id: string | number,
	name: string | number
}
type OrderDetailType = {
  id: number | string,
  itemName: string,
}
type Process = {
  orderDetailId: string | number,
  processingItems: string,
  processingFree: string | number
}

// 计加工
const configID = 543
export default defineComponent({
  name: 'SkillPlusMerit',
  components: {
    ztable,
    zpage,
    zsearch,
    zdrawer,
    ztitleBorder
  },

  setup() {
    const request = useRequet({ path: "" });
    const rowList = useConfgin(configID)
    console.log('计加工', rowList)
    const groupData = rowList.groupDataList.value;
      /** 列表部分 -> 开始 */
    let search = reactive({
      date:'',
      current: 1,
      size: 10,
      total: 0,
      id: null,
      customerId: null,
      loading: false,
      options: [] as OpearBtn[],
      openDrawer: false,
      orderDetailId: '',
      orderDetail: [] as OrderDetailType[],
      medicalHistoryId: '',
      medicalOptions: [] as OpearBtn[],
      processOrderCode: '',
      consigneeId: '',
      consigneeOptions: [] as OpearBtn[],
      companyUserId: '',
      companyUserOptions: [] as OpearBtn[],
      processFactoryId: '',
      processFactoryOptions: [] as OpearBtn[],
      details: [] as Process[],
      title: '新建计加工'
    })
    const data = ref([])
    //搜索
    const hanledSearch = () => {
      debounceRefresh()
    }

    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
			console.log('handleCurrentChange', val)
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
			console.log('handleSizeChange', val)
		}
    const close = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        search.openDrawer = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      close()
    }

    const req = () => {
      let params = {
        current: search.current,
        size: search.size,
        // customId: search.customerId
      }
    search.loading = true
    request.sendRequest({
      address: 'warehouse/processLog/processListByPage',
      params,
      success: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
        data.value = resp.data.records
        search.total = resp.data.total
        search.current = resp.data.current

        search.loading = false
      },
      fail: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取供应商管理列表失败')
        
      },
      method: "POST",
    })
  }
    req()
    const debounceRefresh = debounce(req, 1000)
    
    const getStatus = () => {
      request.sendRequest({
        address: '/warehouse/processLog/getTechnologyProcessStatus',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg )
          search.options = resp.data
          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    getStatus()

    // 单选人
    const clickCell = (val: any) => {
      search.customerId = val.customerId
    }

    // 新建
    const handleClickDrawer = () => {
      if(!search.customerId) {
        ElMessage.warning('请选择用户在操作')
        return false
      } else {
        search.openDrawer = true
      
        search.title = '新建计加工'
        search.medicalHistoryId = ''
        search.processOrderCode = ''
        search.consigneeId = ''
        search.companyUserId = ''
        search.processFactoryId = ''
        search.orderDetailId = ''

        search.details = []
      }
      
    }
    
    // 修改
    const handleEditItem = (rowData: any) => {
      console.log(rowData)
      search.title = '修改计加工'
      let id = rowData.customerId
      search.id = rowData.id
      search.customerId = id
      search.openDrawer = true
      getHistorySelect(id)
      
      getOrderDetail(id)

      search.details = rowData.details
      search.medicalHistoryId = rowData.medicalHistoryId,
      search.processOrderCode = rowData.processOrderCode,
      search.consigneeId = rowData.consigneeId,
      search.companyUserId = rowData.companyUserId,
      search.processFactoryId = rowData.processFactoryId
      search.details = rowData.details
    }
    // 删除
    const handleDelItem = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        request.sendRequest({
          address: `/warehouse/processLog/processDelete/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
            ElMessage.success('删除成功')
            req()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
          },
          method: "POST",
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      });
    }

    // 下拉
    const handleChange = (e: string, rowData: any) => {
      let id = rowData.id
      let val = JSON.parse(JSON.stringify(e))
      changeStatus(val, id)
    } 

    const changeStatus = (status: string, id: string | number) => {
      request.sendRequest({
        address: 'warehouse/processLog/processStatusUpdate',
        params: {
          id,
          status
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          ElMessage.success(resp.msg)
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const getDoctorList = () => {
      // 获取医生
      request.sendRequest({
        address: 'company/user/user/getDoctorUserByStatus',
        params: {
          name: ''
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          search.companyUserOptions = resp.data
          search.consigneeOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }
    

    const getHistorySelect = (id: string | number) => {
      //获取病历下拉
      request.sendRequest({
        address: 'sick/history/getHistorySelect',
        params: {
          customerId: id
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          search.medicalOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }
    
    const getTechnologyPlantList = () => {
      //获取加工厂下拉
      request.sendRequest({
        address: 'warehouse/processLog/getTechnologyPlantList',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          search.processFactoryOptions = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      }) 
    }
    
    const getOrderDetail = (id: string | number) => {
      // 获取客户项目详情
      request.sendRequest({
        address: `/warehouse/processLog/getCustomOrderList/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          // console.log(resp.data)
          search.orderDetail = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      }) 
    }
    
    const addProcess = () => {
      console.log('新增了')
      search.details.push({
        orderDetailId: search.orderDetailId,
        processingItems: '默认',
        processingFree: 1
      })

      console.log(search.details)
    }
    const handleDelete = (index: number) => {
      console.log(index)
      search.details.splice(index, 1)
    }

    const save = () => {
      if(search.title === '新建计加工') {
        request.sendRequest({
        address: '/warehouse/processLog/processAdd',
        params: {
          customerId: search.customerId,
          medicalHistoryId: search.medicalHistoryId,
          processOrderCode: search.processOrderCode,
          consigneeId: search.consigneeId,
          companyUserId: search.companyUserId,
          processFactoryId: search.processFactoryId,
          details: search.details
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('新增' + resp.msg)
          ElMessage.success('新增' + resp.msg)

          search.openDrawer = false
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('新增' + resp.msg)
          
        },
        method: "POST",
      })
      }

      if(search.title === '修改计加工') {
        request.sendRequest({
          address: '/warehouse/processLog/processUpdate',
          params: {
            id: search.id,
            customerId: search.customerId,
            medicalHistoryId: search.medicalHistoryId,
            processOrderCode: search.processOrderCode,
            processFactoryId: search.processFactoryId,
            consigneeId: search.consigneeId,
            companyUserId: search.companyUserId,
            details: search.details
          },
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('修改' + resp.msg)
            ElMessage.success('修改' + resp.msg)

            search.openDrawer = false
            req()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('修改' + resp.msg)
            
          },
          method: "POST",
        })
      }
      
    }

    getDoctorList()
    getTechnologyPlantList()
    if(search.customerId) {
      getHistorySelect(search.customerId)
    }
    
      
    
    search.customerId && getOrderDetail(search.customerId)

    /** 列表部分 -> 结束 */
    return {
      ...toRefs(search),
      data,
      hanledSearch,
      handleCurrentChange,
      handleSizeChange,
      
      handleClickDrawer,
      handleEditItem,
      handleDelItem,
      handleChange,
      clickCell,

      groupData,
      addProcess,
      handleDelete,

      close,
      save,
      cancel,
    }
  }
})
</script>

<style lang="scss" scoped>
.tem {
  height: 60px;
  padding: 0 10px;
  display: block;
  font-size: 14px;
  color: $primaryText;
  
  .tem-title {
    padding-bottom: 5px;
  }
}

.machin-select {
	margin-right: 8px;
}
</style>